<?php 

require_once "core/init.php";
/*echo 'token name...............'.Config::get('session/token_name').'<br/>';  
echo 'post token..................'.input::getToken('token').'<br/>';         
echo 'get session token......'.Session::get('token').'<br/>';
var_dump(Token::check( input::get('token')) ) ; */

	if (Input::exists()) {
			
		if (Token::check(Input::get('token'))) {
			
			 	//echo "this has been run </br>";

			$validate = new Validation();
			$validation = $validate->check($_POST, array(

				'username' => array(
					'required' => true,
					'min' => 2,
					'max' => 20,
					'unique' => 'users'
				),

				'password' => array(
					'required' =>  true,
					'min' => 6
				),

				'password_again' => array(
					'required' =>  true,
					'matches' => 'password'
				),

				'name' => array(
					'required' =>  true,
					'min' => 2,
					'max' => 50
				)

			));

			if ($validation->passed()) {
				//if success some actions here
				//Session::flash('Success', 'you registered successfully!');
				//header('location: index.php');
				$user = new User();

				$salt = Hash::salt(32);

				try {

					$user->create(array(
						'username' => Input::get('username'),
						'password' =>  Hash::make(Input::get('password'), $salt),
						'salt' => $salt,
						'name' => Input::get('name'),
						'joined' => date('Y-m-d H:i:s'),
						'group' => 1
					));

					
					Session::flash('home', 'you registered successfully!');
					Redirect::to('index.php');
					
				} catch (Exception $e) {
					die($e->getMessage());
				}


				//register user
			}else {
				// if run some problems show errors
				//print_r($validation->errors());
				foreach ($validation->errors() as $error) {
					echo $error, '<br/>';
				}
			}

		}

	}

?>


<form action="" method="post">

	<div class="field">
		<label for="username">Username</label>
		<input type="text" name="username" id="username" value="<?php  echo escape(Input::get('username')); ?>" autocomplete="off">
	</div>

	<div class="field">
		<label for="password">Password</label>
		<input type="password" name="password" id="password" value="" autocomplete="off">
	</div>

	<div class="field">
		<label for="password_again"> re type Password</label>
		<input type="password" name="password_again" id="password_again" value="" autocomplete="off">
	</div>

	<div class="field">
		<label for="name">Name</label>
		<input type="text" name="name" id="name" value="<?php  echo escape(Input::get('name')); ?>" autocomplete="off">
	</div>

	<div class="field">
		<input type="submit" value="register">
	</div>

	<div class="field">
		<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
	</div>
</form>